import { Button, Popover, Table } from 'antd'
import { isEmpty } from 'lodash-es'
import { useEffect, useState } from 'react'

import { companionComboListApi, getCompanionComboDetailApi } from '@/api/pcs/pcsCompanionCombo'
import { companionCompanyListApi } from '@/api/pcs/pcsCompanionCompany'
import { getCompanionFlowApi } from '@/api/pcs/pcsCompanionFlow'
import { hospitalAndAreaOptionsApi, submitCompanionPlanApi } from '@/api/pcs/pcsCompanionOrder'
import { inpatientWardListApi } from '@/api/pcs/pcsInpatientWard'
import AekDrawer, { PromiseThen } from '@/components/AekDrawer'
import AekForm from '@/components/AekForm'
import AekModal from '@/components/AekModal'
import AekUpload from '@/components/AekUpload'
import APanel from '@/components/APanel'
import Ellipsis from '@/components/Ellipsis'
import { message, renderIndexColumn } from '@/utils/antdHelper'
import { REGEXP_IDENTITY_CARD } from '@/utils/constants'
import { formatDate, formatMoneyNum } from '@/utils/displayHelper'
import {
  ACCOMPANYING_PERIOD_ENUM,
  GENDER_ENUM,
  PCS_CATHETERCOMPANION_ENUM,
  PCS_COMPANION_PERIOD_ENUM,
  PCS_COMPANION_TYPE_ENUM,
  PCS_COMPANION_WAY_ENUM,
  PCS_CONTENT_AVAILABLEPOPULATION_ENUM,
  PCS_EATINGMETHOD_ENUM,
  PCS_MEDICALSYMPTOMS_ENUM,
  PCS_MEDICATIONASSISTANCE_ENUM,
  PCS_OTHERCOMPANIONSHIP_ENUM,
  PCS_SELFCARESTATUS_ENUM,
} from '@/utils/enum'
import { requestWithTry } from '@/utils/request'
import { dataURLtoFile, uploadFileToOss } from '@/utils/uploadUtil/helper'

import DatePickerWithSelect from '../DatePickerWithSelect'
import NursingWorkerSelect from '../NursingWorkerSelect'
import SignModal from '../SignModal'

const AccompanyingPlanDrawer = ({ detailData = {}, isDetail = false }) => {
  const [form] = AekForm.useForm()

  const hospital = AekForm.useWatch('hospital', form)
  const companionOrderDetail = AekForm.useWatch('companionOrderDetail', form)

  const [sign, setSign] = useState()
  const [companionPackage, setCompanionPackage] = useState({})
  const [processFlowItemList, setProcessFlowItemList] = useState([])

  const getPcsCompanionComboDetail = async id => {
    const { data } = await requestWithTry(getCompanionComboDetailApi, { id })
    const { data: processDetail } = await requestWithTry(getCompanionFlowApi, { id: data.companionFlowId })
    if (!data.enable) return
    if (!data.hospitalAreaIdList?.includes(detailData.areaId)) return
    setCompanionPackage(data)
    setProcessFlowItemList(processDetail.items)
    form.setFieldValue(['companionOrderDetail', 'price'], data.price)
    form.setFieldValue(['companionOrderDetail', 'companionComboId'], String(data.id))
  }

  useEffect(() => {
    if (isEmpty(detailData)) return
    // 制定方案
    if (!isDetail) {
      form.setFieldsValue({
        ...detailData,
        hospital: detailData.hospitalId ? [Number(detailData.hospitalId), Number(detailData.areaId)] : undefined,
      })
      form.setFieldValue(
        ['companionOrderDetail', 'companionType'],
        detailData.orderDetail?.companionType
          ? Number(detailData.orderDetail.companionType)
          : PCS_COMPANION_TYPE_ENUM.HOSPITAL,
      )
      getPcsCompanionComboDetail(detailData.companionComboId)
    } else {
      // 详情
      setCompanionPackage({
        id: detailData.orderDetail.companionComboId,
        name: detailData.orderDetail.companionComboName,
        content: detailData.orderDetail.companionComboContent,
        comboMainImg: detailData.orderDetail.comboMainImg,
        comboDetailImgList: detailData.orderDetail.comboDetailImgList,
        companionWay: detailData.orderDetail.companionComboCompanionWay,
        price: detailData.orderDetail.price,
        comboType: Number(detailData.orderDetail.companionType),
      })
      setProcessFlowItemList(detailData.orderDetail.orderDetailFlowItemList)
    }
    setSign(detailData.orderFile?.fileUrl)
  }, [detailData])

  /** @type {import("@/components/AekForm").FormDataProps[]} */
  const formData = [
    { label: '姓名', view: true, viewRender: () => detailData.patientName },
    {
      field: 'gender',
      label: '性别',
      formItemProps: { rules: [{ required: true }] },
      component: {
        name: 'RadioGroup',
        props: {
          options: GENDER_ENUM.options,
        },
      },
      enum: GENDER_ENUM,
    },
    {
      field: 'idCard',
      label: '身份证号',
      formItemProps: { rules: [{ pattern: REGEXP_IDENTITY_CARD, message: '请输入正确的身份证格式' }] },
      component: { name: 'Input' },
    },
    {
      field: 'phoneNo',
      label: '手机号',
      formItemProps: {
        rules: [{ required: true }],
      },
      component: { name: 'Input' },
    },
    { field: 'medicalRecordNo', label: '病历号', component: { name: 'Input' } },
    { field: 'inpatientNo', label: '住院号', component: { name: 'Input' } },
    { field: 'familyName', label: '家属姓名', component: { name: 'Input' } },
    { field: 'familyPhoneNo', label: '家属电话', component: { name: 'Input' } },
    {
      field: 'remark',
      label: '备注',
      component: { name: 'Input' },
      viewRender: text => (
        <Ellipsis tooltip lines={1}>
          {text || '-'}
        </Ellipsis>
      ),
    },
  ]

  /** @type {import("@/components/AekForm").FormDataProps[]} */
  const formData2 = [
    {
      field: ['companionOrderDetail', 'companionType'],
      label: '陪护类型',
      formItemProps: {
        initialValue: PCS_COMPANION_TYPE_ENUM.HOSPITAL,
        rules: [{ required: true }],
      },
      component: {
        name: 'RadioGroup',
        props: {
          style: { width: '100%' },
          options: PCS_COMPANION_TYPE_ENUM.options,
        },
      },
      viewField: ['orderDetail', 'companionType'],
      enum: PCS_COMPANION_TYPE_ENUM,
    },
    {
      label: '医院',
      field: 'hospital',
      formItemProps: {
        rules: [{ required: true }],
      },
      component: {
        name: 'AekCascader',
        props: {
          api: hospitalAndAreaOptionsApi,
          fieldNames: {
            children: 'areaList',
          },
          onChange: () => {
            setCompanionPackage({})
            form.setFieldValue(['companionOrderDetail', 'companionComboId'], undefined)
            form.setFieldsValue({
              inpatientWardId: undefined,
            })
          },
        },
      },
      viewRender: () => `${detailData.hospitalName}/${detailData.areaName}`,
    },
    {
      field: 'inpatientWardId',
      label: '病区',
      formItemProps: {
        rules: [{ required: true }],
      },
      component: {
        name: 'AekSelect',
        props: {
          allowClear: false,
          api: inpatientWardListApi,
          params: {
            hospitalId: hospital?.[0],
            areaId: hospital?.[1],
          },
        },
      },
      viewRender: () => detailData.inpatientWardName,
    },
    {
      field: 'bedNumber',
      label: '床位',
      formItemProps: {
        rules: [{ required: true }],
      },
      component: {
        name: 'Input',
      },
    },
    {
      label: '陪护公司',
      field: ['companionOrderDetail', 'companionCompanyId'],
      formItemProps: {
        rules: [{ required: true }],
      },
      component: {
        name: 'AekSelect',
        props: {
          allowClear: false,
          api: companionCompanyListApi,
          onChange: () => {
            form.setFieldsValue({
              [['companionOrderDetail', 'nursingWorke']]: undefined,
            })
          },
        },
      },
      viewRender: () => detailData.orderDetail?.companionCompanyName,
    },
    {
      label: '开始时间',
      field: ['companionOrderDetail', 'start'],
      formItemProps: {
        rules: [
          { required: true, message: ' ' },
          {
            validator: async (rule, value) => {
              if (!value || !value?.datePicker || !value?.select) {
                return Promise.reject('请选择开始时间')
              }
              Promise.resolve()
            },
          },
        ],
      },
      component: (
        <DatePickerWithSelect
          onChange={() => {
            form.setFieldsValue({
              [['companionOrderDetail', 'end']]: undefined,
            })
          }}
        />
      ),
      viewRender: () =>
        `${formatDate(detailData.orderDetail?.startDate)} ${PCS_COMPANION_PERIOD_ENUM.getText(
          detailData.orderDetail?.startPeriod,
        )}`,
    },
    {
      label: '结束时间',
      field: ['companionOrderDetail', 'end'],
      formItemProps: {
        rules: [
          {
            validator: async (rule, value) => {
              if (!value || !value?.datePicker || !value?.select) {
                return Promise.reject('请选择结束时间')
              }
              Promise.resolve()
            },
          },
        ],
      },
      component: (
        <DatePickerWithSelect
          disabled={!companionOrderDetail?.start?.datePicker || !companionOrderDetail?.start?.select}
          disabledDate={current =>
            current &&
            ((companionOrderDetail?.start?.select === PCS_COMPANION_PERIOD_ENUM.BEFORE12 &&
              current < companionOrderDetail?.start?.datePicker?.startOf('d')) ||
              (companionOrderDetail?.start?.select === PCS_COMPANION_PERIOD_ENUM.AFTER12 &&
                current <= companionOrderDetail?.start?.datePicker?.endOf('d')))
          }
          disabledSelect={value =>
            value === PCS_COMPANION_PERIOD_ENUM.BEFORE12 &&
            companionOrderDetail?.start?.datePicker?.startOf('d').valueOf() ===
              companionOrderDetail?.end?.datePicker?.startOf('d').valueOf() &&
            companionOrderDetail?.start?.select === PCS_COMPANION_PERIOD_ENUM.BEFORE12
          }
        />
      ),
      viewRender: () =>
        `${formatDate(detailData.orderDetail?.endDate) || ''} ${
          PCS_COMPANION_PERIOD_ENUM.getText(detailData.orderDetail?.endPeriod) || ''
        }`,
    },
    {
      field: ['companionOrderDetail', 'servicePeriod'],
      label: '陪护时段',
      formItemProps: {
        initialValue: ACCOMPANYING_PERIOD_ENUM.ALL_DAY,
        rules: [{ required: true, message: '必填项' }],
      },
      component: {
        name: 'Select',
        props: {
          style: { width: '100%' },
          options: ACCOMPANYING_PERIOD_ENUM.options,
        },
      },
      viewRender: () => ACCOMPANYING_PERIOD_ENUM.getText(detailData.orderDetail?.servicePeriod),
    },
    {
      field: ['companionOrderDetail', 'nursingWorke'],
      label: '护工',
      formItemProps: {
        rules: [{ required: true, message: '必填项' }],
      },
      component: (
        <NursingWorkerSelect
          {...{
            disabled: !companionOrderDetail?.companionCompanyId,
            companionType: companionOrderDetail?.companionType,
            companionCompanyId: companionOrderDetail?.companionCompanyId,
            patientName: detailData.patientName,
            phoneNo: detailData.phoneNo,
            orderNo: detailData.orderNo,
          }}
        />
      ),
      viewRender: () => (
        <Popover
          content={
            <Table
              rowKey='id'
              bordered
              columns={[
                { dataIndex: 'nursingWorkersName', title: '姓名' },
                { dataIndex: 'nursingWorkersPhoneNo', title: '电话' },
                {
                  dataIndex: 'time',
                  title: '服务时间',
                  render: (_, { startDate, startPeriod, endDate, endPeriod }) =>
                    `${formatDate(startDate)} ${PCS_COMPANION_PERIOD_ENUM.getText(startPeriod)} ~ ${formatDate(
                      endDate,
                    )} ${PCS_COMPANION_PERIOD_ENUM.getText(endPeriod)}`,
                },
              ]}
              dataSource={detailData.orderDetail?.orderDetailNursingWorkerList || []}
              pagination={false}
            />
          }
        >
          <a>{detailData.orderDetail?.orderDetailNursingWorkerList?.[0]?.nursingWorkersName}</a>
        </Popover>
      ),
    },
    {
      label: '护工电话',
      view: true,
      viewRender: () =>
        isDetail
          ? detailData.orderDetail?.orderDetailNursingWorkerList?.[0]?.nursingWorkersPhoneNo
          : companionOrderDetail?.nursingWorke?.phoneNo,
    },
    {
      field: ['companionOrderDetail', 'companionComboId'],
      label: '套餐名称',
      formItemProps: {
        rules: [{ required: true, message: '必填项' }],
      },
      component: {
        name: 'AekSelect',
        props: {
          api: companionComboListApi,
          allowClear: false,
          params: {
            enable: true,
            // comboType: detailData.comboType,
            // homeAreaId,
            hospitalAreaId: hospital?.[1],
          },
          onChange: id => {
            getPcsCompanionComboDetail(id)
          },
        },
      },
      viewRender: () => companionPackage.name,
    },
    {
      label: '套餐内容',
      view: true,
      viewRender: () => (
        <Ellipsis tooltip lines={1}>
          {companionPackage.content}
        </Ellipsis>
      ),
    },
    {
      label: '套餐主图',
      view: true,
      viewRender: () => (
        <AekUpload
          listType='picture-card'
          value={companionPackage.comboMainImg}
          showUploadList={{ showRemoveIcon: false }}
          limitFileNum={0}
        />
      ),
    },
    {
      label: '套餐详情',
      view: true,
      viewRender: () => (
        <AekUpload
          listType='picture-card'
          stackingThumb
          value={companionPackage.comboDetailImgList}
          showUploadList={{ showRemoveIcon: false }}
          limitFileNum={0}
        />
      ),
    },
    {
      label: '陪护方式',
      view: true,
      viewRender: () => PCS_COMPANION_WAY_ENUM.getText(companionPackage.companionWay),
    },
    {
      field: ['companionOrderDetail', 'price'],
      label: '收费标准',
      formItemProps: {
        rules: [
          { required: true },
          {
            pattern: /^[0-9]*$/i,
            message: '请输入整数',
          },
        ],
      },
      component: {
        name: 'AekInputNumber',
        props: {
          min: 0,
        },
      },
      other: '/天',
      viewRender: () => (detailData.orderDetail?.price ? `${formatMoneyNum(detailData.orderDetail?.price)}/天` : ''),
    },
  ]

  /** @type {import("@/components/AekForm").FormDataProps[]} */
  const formData3 = [
    {
      field: ['companionOrderPatientLabel', 'selfCareStatus'],
      label: '自理情况',
      formItemProps: {
        rules: [{ required: true, message: '必填项' }],
      },
      component: {
        name: 'RadioGroup',
        props: {
          options: PCS_SELFCARESTATUS_ENUM.options,
        },
      },
      viewRender: () => PCS_SELFCARESTATUS_ENUM.getText(detailData.orderPatientLabel?.selfCareStatus),
    },
    {
      field: ['companionOrderPatientLabel', 'medicalSymptoms'],
      label: '病情症状',
      formItemProps: {
        rules: [{ required: true, message: '必填项' }],
      },
      component: {
        name: 'CheckboxGroup',
        props: {
          options: PCS_MEDICALSYMPTOMS_ENUM.options,
        },
      },
      viewRender: () =>
        (detailData.orderPatientLabel?.medicalSymptoms || [])
          .map(text => PCS_MEDICALSYMPTOMS_ENUM.getText(text))
          .join('、'),
    },
    {
      field: ['companionOrderPatientLabel', 'eatingMethod'],
      label: '进食方式',
      formItemProps: {
        rules: [{ required: true, message: '必填项' }],
      },
      component: {
        name: 'RadioGroup',
        props: {
          options: PCS_EATINGMETHOD_ENUM.options,
        },
      },
      viewRender: () => PCS_EATINGMETHOD_ENUM.getText(detailData.orderPatientLabel?.eatingMethod),
    },
    {
      field: ['companionOrderPatientLabel', 'catheterCompanions'],
      label: '导管陪护',
      formItemProps: {
        rules: [{ required: true, message: '必填项' }],
      },
      component: {
        name: 'CheckboxGroup',
        props: {
          options: PCS_CATHETERCOMPANION_ENUM.options,
        },
      },
      viewRender: () =>
        (detailData.orderPatientLabel?.catheterCompanions || [])
          .map(text => PCS_CATHETERCOMPANION_ENUM.getText(text))
          .join('、'),
    },
    {
      field: ['companionOrderPatientLabel', 'medicationAssistance'],
      label: '药物协助',
      formItemProps: {
        rules: [{ required: true, message: '必填项' }],
      },
      component: {
        name: 'CheckboxGroup',
        props: {
          options: PCS_MEDICATIONASSISTANCE_ENUM.options,
        },
      },
      viewRender: () =>
        (detailData.orderPatientLabel?.medicationAssistance || [])
          .map(text => PCS_MEDICATIONASSISTANCE_ENUM.getText(text))
          .join('、'),
    },
    {
      field: ['companionOrderPatientLabel', 'otherCompanionship'],
      label: '其它陪护',
      formItemProps: {
        rules: [{ required: true, message: '必填项' }],
      },
      component: {
        name: 'CheckboxGroup',
        props: {
          options: PCS_OTHERCOMPANIONSHIP_ENUM.options,
        },
      },
      viewRender: () =>
        (detailData.orderPatientLabel?.otherCompanionship || [])
          .map(text => PCS_OTHERCOMPANIONSHIP_ENUM.getText(text))
          .join('、'),
    },
  ]

  const tableColumns = [
    renderIndexColumn(),
    { dataIndex: 'time', title: '时间', render: (_, { startTime, endTime }) => `${startTime} ~ ${endTime}` },
    { dataIndex: 'companionContentName', title: '陪护内容' },
    {
      dataIndex: 'availablePopulation',
      title: '适用对象',
      render: text => PCS_CONTENT_AVAILABLEPOPULATION_ENUM.getText(text),
    },
  ]

  const onSign = async () => {
    await AekModal.PromiseThen({
      title: '知情同意书',
      okText: '下一步',
      children: (
        <div className='text-14px'>
          <div>
            <span className='font-bold'>服务内容：</span>
            本确认书涉及的服务包括但不限于病人的日常照料、医疗协助、情感支持等。
          </div>
          <div className='mt20px'>
            <span className='font-bold'>取消与更改政策：</span>若需取消或更改服务，请至少提前24
            小时通知我们。根据取消或更改的时间点， 可能会收取一定比例的服务费用作为违约金。
          </div>
          <div className='mt20px'>
            <span className='font-bold'>责任与保障：</span>
            我们的护工均经过专业培训，并由公司承担责任保险。如在服务过程中发生意外，
            请及时与我们联系，我们将按照相关法律法规和公司政策进行处理。
          </div>
          <div className='mt20px'>
            <span className='font-bold'>隐私保护：</span>
            我们承诺保护您的个人信息安全，不会未经您的同意向第三方透露您的个人资料。
          </div>
          <div className='mt20px font-bold'>
            请您在仔细阅读并理解上述条款后，在下方签名确认。您的签名意味着您已阅读、理解并同意所有条款和服务内容。
          </div>
        </div>
      ),
    })

    const sign = await SignModal.PromiseThen()
    setSign(sign)
  }

  const onSubmit = async () => {
    const values = await form.validateFields()
    if (!sign) {
      message.warning('请签字')
      return
    }
    const fileName = `${detailData.orderNo}-签名`
    const file = dataURLtoFile(sign, fileName)
    await uploadFileToOss(file)
    const { hospital, companionOrderDetail, ...otherValues } = values
    const { start, end, nursingWorke, ...otherCompanionOrderDetail } = companionOrderDetail
    const params = {
      id: detailData.id,
      ...otherValues,
      hospitalId: hospital[0],
      areaId: hospital[1],
      companionOrderDetail: {
        ...otherCompanionOrderDetail,
        startDate: formatDate(start.datePicker),
        startPeriod: start.select,
        endDate: formatDate(end?.datePicker),
        endPeriod: end?.select,
        nursingWorkersId: nursingWorke.id,
      },
      file: {
        fileName: file.name,
        fileUrl: file.url,
      },
    }
    await requestWithTry(submitCompanionPlanApi, params)
  }

  return (
    <AekDrawer title={isDetail ? '方案详情' : '制定方案'} showFooter={!isDetail} width='90%' onOk={onSubmit}>
      <APanel title='患者信息'>
        <AekForm allView={isDetail} detail={detailData} form={form} formData={formData} col={8} />
      </APanel>
      <APanel title='服务信息'>
        <AekForm allView={isDetail} detail={detailData} form={form} formData={formData2} col={6} />
      </APanel>
      <APanel title='服务流程'>
        <Table rowKey='id' pagination={false} columns={tableColumns} dataSource={processFlowItemList} />
      </APanel>
      <APanel title='病患标签'>
        <AekForm allView={isDetail} detail={detailData} form={form} formData={formData3} />
      </APanel>
      <APanel title='客户签字'>
        <div>
          {(sign || isDetail) && <img src={sign} alt='' width={400} />}
          {!isDetail && <Button onClick={onSign}> {sign ? '重新签字' : '签字'}</Button>}
        </div>
      </APanel>
    </AekDrawer>
  )
}

AccompanyingPlanDrawer.PromiseThen = PromiseThen

export default AccompanyingPlanDrawer
